package com.corner.utils.view;

import android.os.Handler;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.corner.app.GlobalParams;
import com.corner.utils.AudioRecorder;
import com.corner.utils.DateFormatUtil;

/**
 * 关于语音按钮的长按录音的功能提取
 *
 * @author Administrator
 */
public class AudioHelper implements OnTouchListener {

    /******************************
     * 回调接口
     *******************************/
    public int timeLeft = 10;
    private boolean isRecording;
    private AudioRecorder audioRecorder;
    private RecoderNoticeCallback recoderNoticeCallback;
    private float downY;
    private long startTime;
    private boolean isShowCancel = false;
    private View btnPressAudio;
    private String currentAudioPath;

    /******************************
     * 回调接口
     *******************************/
    private int MAX_DURATION = 60;
    private OnFinishRecordCallback callback;
    // 处理倒计时
    public Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            if (timeLeft != 0 && isRecording) {
                sendEmptyMessageDelayed(0, 1000);
                // 获取音量，更新Dialog
                if (recoderNoticeCallback != null) {
                    recoderNoticeCallback.update(timeLeft--, isShowCancel);
                }
            } else if (isRecording) {
                timeLeft = 10;
                isRecording = false;
                if (audioRecorder != null) {
                    audioRecorder.stop();
                }
                audioRecorder = null;
                finishToSendAudio(true);
            }
        }
    };

    /**
     * @param btnPressAudio
     * @param callback
     */
    public AudioHelper(View btnPressAudio, OnFinishRecordCallback callback) {
        super();
        this.btnPressAudio = btnPressAudio;
        this.callback = callback;
        btnPressAudio.setOnTouchListener(this);
    }

    /**
     * 获取当前录音文件的路径
     *
     * @return
     */
    private String getAudioPath() {
        return GlobalParams.APPFIEPATH + "/audio/"
                + DateFormatUtil.getCurrentTimeInMills() + ".amr";
    }

    public RecoderNoticeCallback getRecoderNoticeCallback() {
        return recoderNoticeCallback;
    }

    public void setRecoderNoticeCallback(
            RecoderNoticeCallback recoderNoticeCallback) {
        this.recoderNoticeCallback = recoderNoticeCallback;
    }

    /**
     * 结束录音，发送语音
     *
     * @param sucess
     */
    private void finishToSendAudio(boolean sucess) {
        if (recoderNoticeCallback != null) {
            recoderNoticeCallback.finishShowVoiceDialog();
        }
        if (callback != null) {
            if (sucess) {
                callback.finish(true, currentAudioPath);
            } else {
                callback.finish(false, null);
            }
        }
        currentAudioPath = null;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                btnPressAudio.setPressed(true);
                downY = event.getY();
                currentAudioPath = getAudioPath();
                // 手指放下时，开始录音
                try {
                    if (audioRecorder == null) {
                        audioRecorder = new AudioRecorder(currentAudioPath,
                                MAX_DURATION);
                    }
                    audioRecorder.setPath(currentAudioPath);
                    audioRecorder.start();
                    isRecording = true;
                    handler.sendEmptyMessageDelayed(0, 50000);
                    startTime = SystemClock.uptimeMillis();
                    // 开启对话框通知
                    if (recoderNoticeCallback != null) {
                        recoderNoticeCallback
                                .showVoiceDialog(RecoderNoticeCallback.SHOW_VOICE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isRecording) {
                    break;
                }
                float f = downY - event.getY();
                if (f > v.getHeight()) {
                    // 滑出了Button，去显示取消的对话框
                    isShowCancel = true;
                    if (recoderNoticeCallback != null) {
                        recoderNoticeCallback
                                .showVoiceDialog(RecoderNoticeCallback.SHOW_CANCEL);
                    }
                } else if (f < v.getHeight() && f > 5
                        && recoderNoticeCallback != null) {
                    isShowCancel = false;
                    // 没有滑出Button
                    if (timeLeft == 10) {
                        recoderNoticeCallback
                                .showVoiceDialog(RecoderNoticeCallback.SHOW_VOICE);
                    } else {
                        recoderNoticeCallback.update(timeLeft, isShowCancel);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                btnPressAudio.setPressed(false);
                if (!isRecording) {
                    break;
                }
                // 如果还在录音，停止录音
                if (audioRecorder != null) {
                    audioRecorder.stop();
                    audioRecorder = null;
                }
                if (SystemClock.uptimeMillis() - startTime < 1000) {
                    if (recoderNoticeCallback != null) {
                        recoderNoticeCallback.showWarnToast();
                        recoderNoticeCallback.finishShowVoiceDialog();
                        handler.removeMessages(0);
                    }
                    finishToSendAudio(false);
                } else if (isShowCancel) {
                    if (recoderNoticeCallback != null) {
                        recoderNoticeCallback.finishShowVoiceDialog();
                    }
                    finishToSendAudio(false);
                } else {
                    finishToSendAudio(true);
                }
                timeLeft = 10;
                isRecording = false;
                break;
        }
        return false;
    }

    /**
     * 录音提醒功能回调,交给外面的Activity去显示对话框和Toast
     *
     * @author Administrator
     */
    public interface RecoderNoticeCallback {
        int SHOW_VOICE = 1;
        int SHOW_CANCEL = 2;

        /**
         * 显示录音的Dialog
         *
         * @param flag :若为1，显示此时的音量，若为2，显示取消录音
         */
        void showVoiceDialog(int flag);

        /**
         * 更新Dialog
         *
         * @param voice
         */
        void update(int voice, boolean isShowCancel);

        /**
         * 录音时间太短，显示警告Toast
         */
        void showWarnToast();

        /**
         * 结束显示对话框
         */
        void finishShowVoiceDialog();

    }

    public interface OnFinishRecordCallback {
        void finish(boolean isOk, String path);
    }

}
